package db_main

import (
	"longmen/server/config/global"
	"longmen/server/pkg/db/mysql/models/models_main"
	"time"

	"gorm.io/gorm"
)

func SaveUserItem(tx *gorm.DB, noble_id int, uid int, propsID int, ptype int, quantity int, name string, remark string, dur int64) error {
	// var selected = 0
	// if ptype == 102 {
	// 	selected = 1
	// }
	var err error
	r := &models_main.UserBackpackStatistics{
		Type:        uint8(ptype),
		Uid:         uid,
		Gid:         propsID,
		Quantity:    quantity,
		ProductName: name,
		Remark:      remark,
		// Selected:    uint8(selected),
		EffTime: time.Now().Unix(),
		ExpTime: time.Now().Unix() + dur,
		NobleID: noble_id,
	}

	record, _ := UserBackpackItem(uid, propsID, ptype)
	if record.Id == 0 {
		// if ptype == 102 {
		// 	err := tx.Model(&models.UserBackpackStatistics{}).
		// 		Where("uid=? and type=102 and gid not in (?)", uid, propsID).
		// 		Update("selected", 0).Error
		// 	if err != nil {
		// 		return err
		// 	}
		// }

		r.ExpTime = time.Now().Unix() + dur
		err = tx.Model(&models_main.UserBackpackStatistics{}).Create(&r).Error
		if err != nil {
			return err
		}
	} else {
		// 坐骑
		if ptype == 102 {
			// err := tx.Model(&models.UserBackpackStatistics{}).
			// 	Where("uid=? and type=102 and gid not in (?)", uid, propsID).
			// 	Update("selected", 0).Error
			// if err != nil {
			// 	return err
			// }
			err = tx.Model(&models_main.UserBackpackStatistics{}).
				Where("id=?", record.Id).
				Updates(map[string]interface{}{
					"eff_time": time.Now().Unix(),
					"exp_time": gorm.Expr(`
						CASE
							WHEN exp_time < ? THEN ?
							ELSE exp_time + ?
						END
						`, time.Now().Unix(), time.Now().Unix()+dur, dur),
				}).Error
			if err != nil {
				return err
			}
		} else {
			err := tx.Model(&models_main.UserBackpackStatistics{}).
				Where("id=?", record.Id).
				Updates(map[string]interface{}{
					"quantity": gorm.Expr("quantity+?", quantity),
				}).Error
			if err != nil {
				return err
			}
		}
	}

	//log.Println("ptype1:", ptype)

	// 将用户最高等级的坐骑选中
	if ptype == 102 {

		//log.Println("ptype2:", ptype)
		err := tx.Model(&models_main.UserBackpackStatistics{}).
			Where("uid=? and type=102", uid).
			Update("selected", 0).Error
		if err != nil {
			return err
		}

		err = tx.Model(&models_main.UserBackpackStatistics{}).
			Where("uid=? and type=102 and exp_time>=?", uid, time.Now().Unix()).
			Order("noble_id desc").Limit(1).
			Update("selected", 1).Error
		if err != nil {
			return err
		}
	}

	return nil
}

func UserBackpackItem(uid int, gid int, ptype int) (*models_main.UserBackpackStatistics, error) {
	r := &models_main.UserBackpackStatistics{}

	err := global.GetR().Model(&models_main.UserBackpackStatistics{}).Where("uid=? and gid=? and type=?", uid, gid, ptype).Order("id asc").
		Limit(1).
		Find(&r).Error

	if err != nil {
		return nil, err
	}

	return r, nil
}
